package com.bdqn.service.impl;

import java.util.*;


import com.bdqn.component.ArticleStatus;
import com.bdqn.component.BlogConstants;
import com.bdqn.dao.ArticleMapper;
import com.bdqn.dao.UserMapper;
import com.bdqn.entity.Article;
import com.bdqn.entity.UserWithBLOBs;
import com.bdqn.service.AlbumService;
import com.bdqn.service.ArticleService;
import com.bdqn.service.CommentService;
import com.bdqn.service.UserService;
import com.bdqn.util.*;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Service("userService")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private ArticleService articleService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private AlbumService albumService;

    @Override
    public Result register(UserWithBLOBs user, String repassword, String captcha, String sysCaptcha) {

        if (StringUtils.isBlank(captcha) || StringUtils.isBlank(sysCaptcha) || !sysCaptcha.equals(captcha)) {
            return Result.createError("请输入有效的验证码");
        }
        if (user == null || StringUtils.isBlank(repassword) || StringUtils.isBlank(user.getEmail())
            || StringUtils.isBlank(user.getPassword()) || !user.getPassword().equals(repassword)) {
            return Result.createError("参数错误");
        }

        //解密
        String str = new String(Base64.getDecoder().decode(user.getPassword()));
        if (!str.contains("-")) {
            return Result.createError("非法操作");
        }

        String strs[] = str.split("-");
        if (!TokenUtil.encodeStr.equals(strs[1])) {
            return Result.createError("非法操作");
        }
        user.setPassword(MD5.md5(strs[0].getBytes()));

        //验证邮箱是否已存在
        if (userMapper.selectCountByEmail(user.getEmail()) > 0) {
            return Result.createError("此邮箱已经被注册");
        }

        user.setCreatetime(new Date());
        user.setStatus(0);
        user.setPhotourl("/static/client/img/header.png");
        user.setCenterpath(System.currentTimeMillis() + "");
        user.setUuid(UUID.randomUUID().toString().replace("-", "").toUpperCase());

        if (userMapper.insert(user) > 0) {
            return Result.createSuccess("注册成功");
        }
        return Result.createError("注册失败");
    }

    @Override
    public Result<UserWithBLOBs> checkLogin(UserWithBLOBs user, String captcha, String sysCaptcha) {

        if (StringUtils.isBlank(captcha) || StringUtils.isBlank(sysCaptcha) || !sysCaptcha.equals(captcha)) {
            return Result.createError("请输入有效的验证码");
        }
        if (user == null || StringUtils.isBlank(user.getEmail()) || StringUtils.isBlank(user.getPassword())) {
            return Result.createError("参数错误");
        }
        //解密
        String str = new String(Base64.getDecoder().decode(user.getPassword()));
        if (!str.contains("-")) {
            return Result.createError("非法操作");
        }
        String strs[] = str.split("-");
        if (!TokenUtil.encodeStr.equals(strs[1])) {
            return Result.createError("非法操作");
        }
        //数据库不嫩保存明码；
        user.setPassword(MD5.md5(strs[0].getBytes()));
        user = userMapper.selectUserByEmailPass(user);
        if (user != null) {
            if (user.getStatus() != 0) {
                return Result.createError("此账号已经被禁用 ");
            }
            user.setPassword(null);
            return Result.createSuccess(user, "登录成功");
        }

        return Result.createError("账户名或密码错误");
    }

    @Override
    public Result updateUserInfo(HttpServletRequest request, UserWithBLOBs user, String[] hobbys, CommonsMultipartFile file, CommonsMultipartFile bannerFile) {

        if (user == null) {
            return Result.createError("参数错误");
        }
        if (!ArrayUtils.isEmpty(hobbys)) {
            String temp = "";
            for (String str : hobbys) {
                temp += str + ",";
            }
            user.setHobby(temp);
        }
        FileResult fs=null;
        if (file != null) {
             fs = FileUtil.saveFileToPath(request, file, BlogConstants.WECHAT_SAVE_PATH, BlogConstants.WECHAT_MAPPING_URL);
            if (fs != null) {
                user.setWechat(fs.getHttpUrl());
            }
        }
        FileResult fs1=null;
        if (bannerFile != null) {
             fs1 = FileUtil.saveFileToPath(request, bannerFile, BlogConstants.BANNER_SAVE_PATH, BlogConstants.BANNER_MAPPING_URL);
            if (fs1 != null) {
                user.setBannerbg(fs1.getHttpUrl());
            }
        }

        UserWithBLOBs loginUser = (UserWithBLOBs) request.getSession().getAttribute(BlogConstants.LOGIN_SESSION_KEY);
        if (!user.getCenterpath().equals(loginUser.getCenterpath())) {
            if (userMapper.selectCountUserByCenterPath(user.getCenterpath()) > 0) {
                return Result.createError("访问名称已经存在，请使用其他名称");
            }
        }
        user.setUuid(loginUser.getUuid());

        if (userMapper.updateByPrimaryKeySelective(user) > 0) {
            if (fs != null ) {
                String oringUrl = loginUser.getWechat();
                FileUtil.deleteFile(request,oringUrl,BlogConstants.WECHAT_SAVE_PATH);
            }
            if (fs1 != null) {
                String oringBanerbg = loginUser.getBannerbg();
                FileUtil.deleteFile(request,oringBanerbg,BlogConstants.BANNER_SAVE_PATH);
            }
            loginUser = userMapper.selectByPrimaryKey(loginUser.getUuid());
            loginUser.setPassword(null);
            request.getSession().setAttribute(BlogConstants.LOGIN_SESSION_KEY, loginUser);
            return Result.createSuccess("修改成功");
        }
        ;

        if (fs != null && fs.getFile().exists()) {
            fs.getFile().delete();
        }
        if (fs1 != null && fs1.getFile().exists()) {
            fs1.getFile().delete();
        }
        return Result.createError("修改失败");
    }

    @Override
    public Result updateUserPhoto(HttpServletRequest request, CommonsMultipartFile file) {

        UserWithBLOBs loginUser = (UserWithBLOBs) request.getSession().getAttribute(BlogConstants.LOGIN_SESSION_KEY);
        String oringUrl = loginUser.getPhotourl();
        FileResult fs = FileUtil.saveFileToPath(request, file, BlogConstants.PHOTO_SAVE_PATH, BlogConstants.PHOTO_MAPPING_URL);
        if (fs != null) {
            loginUser.setPhotourl(fs.getHttpUrl());
            System.out.println(fs.getHttpUrl());
        }

        if (userMapper.updateByPrimaryKeySelective(loginUser) > 0) {
            request.getSession().setAttribute(BlogConstants.LOGIN_SESSION_KEY, loginUser);
            FileUtil.deleteFile(request, oringUrl, BlogConstants.PHOTO_SAVE_PATH);
            return Result.createSuccess("头像修改成功");
        }
        ;

        return Result.createError("头像修改失败");
    }

    @Override
    public Result updatePass(String originPass, String pass, String repass, HttpServletRequest request) {

        if (StringUtils.isBlank(originPass) || StringUtils.isBlank(pass) || StringUtils.isBlank(repass)) {
            return Result.createError("参数错误");
        }

        //解密
        Result<String> rs = checkEncodeStr(originPass);
        System.out.println(rs);
        if (rs.isSuccess()) {
            originPass = rs.getData();
        } else {
            return rs;
        }
        rs = checkEncodeStr(pass);
        if (rs.isSuccess()) {
            pass = rs.getData();
        } else {
            return rs;
        }
        rs = checkEncodeStr(repass);
        if (rs.isSuccess()) {
            repass = rs.getData();
        } else {
            return rs;
        }

        if (!pass.equals(repass)) {
            return Result.createSuccess("两次密码不一致");
        }

        UserWithBLOBs loginUser = (UserWithBLOBs) request.getSession().getAttribute(BlogConstants.LOGIN_SESSION_KEY);
        loginUser = userMapper.selectByPrimaryKey(loginUser.getUuid());
        if (!loginUser.getPassword().equals(originPass)) {
            return Result.createSuccess("原密码错误");
        }
        loginUser.setPassword(pass);
        if (userMapper.updateByPrimaryKeySelective(loginUser) > 0) {
            loginUser.setPassword(null);
            request.getSession().setAttribute(BlogConstants.LOGIN_SESSION_KEY, loginUser);
            return Result.createSuccess("修改成功");
        }
        ;


        return Result.createError("修改失败");
    }

    @Override
    public UserWithBLOBs getUserByCenterPath(String centerPath) {
        UserWithBLOBs user = userMapper.selectByCenterPath(centerPath);
        user.setUuid(null);
        user.setCreatetime(null);
        user.setPassword(null);
        user.setPhone(null);
        user.setStatus(null);
        return user;
    }

    @Override
    public Result userCenter(String centerpath, String pageName, Integer pageIndex, Integer articeTid,
                             HttpSession session) {

        UserWithBLOBs user = userMapper.selectByCenterPath(centerpath);
        if (user == null) {
            return Result.createError("访问地址错误");
        }
        session.setAttribute(BlogConstants.USER_SESSION_KEY,user);
        Map<String, Object> param = new HashMap<String, Object>();
        Page<Article> page = null;
        if ("index".equals(pageName)) {
            page = new Page<>(pageIndex, 5);
            param.put("type", 0);
            param.put("statusList", Arrays.asList(ArticleStatus.AVAILABLR.getValue()));
            param.put("articleTypeId", articeTid);
            param.put("userid", user.getUuid());

            page.setCount(articleMapper.selectCount1(param));

            param.put("start", (pageIndex - 1) * page.getPageSize());
            param.put("row", page.getPageSize());
            page.setDataList(articleMapper.selectList1(param));

            user.setUuid(null);
            user.setCreatetime(null);
            user.setPassword(null);
            user.setPhone(null);
            user.setStatus(null);

            return Result.createSuccess(page);

        } else if ("whisper".equals(pageName)) {
            return articleService.getPageWhisper(pageIndex,3,session,user);
        } else if ("leacots".equals(pageName)) {
          return   commentService.getPageCommentsBycenterpath(pageIndex, centerpath);
        } else if ("album".equals(pageName)) {
            return Result.createSuccess(albumService.getPageAlbum(false,null,null,pageIndex, 10,user));
        } else if ("about".equals(pageName)) {
            return Result.createSuccess(user);
        }

        return null;
    }


    /**
     * 检查密码有效性和解密
     *
     * @param pass
     * @return
     */
    private Result<String> checkEncodeStr(String pass) {
        //解密
        String str = new String(Base64.getDecoder().decode(pass));
        if (!str.contains("-")) {
            return Result.createError("非法操作");
        }

        String strs[] = str.split("-");
        if (!TokenUtil.encodeStr.equals(strs[1])) {
            return Result.createError("非法操作");
        }
        System.out.println(MD5.md5(strs[0].getBytes()) + "解密");
        return Result.createSuccess(MD5.md5(strs[0].getBytes()), "");
    }


}
